package com.github.tetrisgame.utils;

import android.net.Uri;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;

public class TakePhotoUtils {
    public static TakePhotoUtils sharedInstance = new TakePhotoUtils();
    private WeakReference<AppCompatActivity> weakActivity;
    private ActivityResultLauncher<Uri> mLauncher;
    private OnGetUriListener onGetUriListener;

    private TakePhotoUtils() {
    }

    public void init(AppCompatActivity activity) {
        weakActivity = new WeakReference<>(activity);
        mLauncher = activity.registerForActivityResult(new ActivityResultContracts.TakePicture(), result -> {
            if (result) {
                File file = new File(activity.getFilesDir(), "head.jpg");
                Uri uri = Uri.fromFile(file);
                if (onGetUriListener != null) {
                    try {
                        onGetUriListener.getUri(uri);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            } else {

            }
        });
    }

    public void openCamera(OnGetUriListener listener) {
        this.onGetUriListener = listener;
        File file = new File(weakActivity.get().getFilesDir(), "head.jpg");
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri uri = FileProvider.getUriForFile(weakActivity.get(),
                "com.github.tetrisgame.fileprovider",
                file);
        mLauncher.launch(uri);
    }

    public interface OnGetUriListener {
        void getUri(Uri uri) throws FileNotFoundException;
    }
}
